<template>
  <view class="uni-container food-merchant-list">

    <uni-popup ref="message" type="message">
				<uni-popup-message type="error" :message="messageText" :duration="1500"></uni-popup-message>
		</uni-popup>

    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="store_name" label="店铺名称" required>
        <uni-easyinput placeholder="请输入店铺名称，2-20位组成" v-model="formData.store_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="city_code" label="所属城市" required>
        <uni-data-picker v-model="formData.city_code" placeholder="请选择城市" popup-title="请选择城市" :step-searh="true" self-field="code" parent-field="parent_code" @change="(e)=>formData.city_id_array=e.detail.value" collection="admin-city-china" field="name as text, code as value" orderby="value asc"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="store_icon" label="店铺图标" required>
        <uni-file-picker ref="files1"  @select="(e)=>fileList1=e" @delete="()=>fileList1=null" :auto-upload="false" file-mediatype="image" file-extname="jpg,png" :limit="1" return-type="array" v-model="formData.store_icon"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="store_plaque_icon" label="店铺牌匾" required>
        <uni-file-picker ref="files2" @select="(e)=>fileList2=e" @delete="()=>fileList2=null" :auto-upload="false" file-mediatype="image" file-extname="jpg,png" :limit="1" return-type="array" v-model="formData.store_plaque_icon"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="store_cover_icon" label="店铺封面" required>
        <uni-file-picker ref="files3" @select="(e)=>fileList3=e" @delete="()=>fileList3=null" :auto-upload="false" file-mediatype="image" file-extname="jpg,png" :limit="1" return-type="array" v-model="formData.store_cover_icon"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="store_phone" label="店铺电话" required>
        <uni-easyinput placeholder="请输入店铺联系电话" v-model="formData.store_phone" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="store_category_menuId" label="店铺类型" required>
        <uni-data-checkbox mode="button" :multiple="true" v-model="formData.store_category_menuId" :localdata="formOptions.store_category_menuId_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="store_work_date" label="营业日期" required>
        <uni-data-checkbox mode="button" :multiple="true" v-model="formData.store_work_date" :localdata="formOptions.store_work_date_localdata"></uni-data-checkbox>
      </uni-forms-item>

      <uni-forms-item name="store_work_time" label="营业时段"  class="alignFlexStart" required>
        <div class="flexColumn">
          <div class="mySelectBox" v-for="(item,index) in store_work_time" :key="index">
            <select v-model="store_work_time[index].startH" class="mySelect">
              <option :value="it.value" v-for="(it,i) in hourOptions" :key="i">{{it.name}}</option>
            </select>
            <div class="symbol_1">:</div>
            <select v-model="store_work_time[index].startM" class="mySelect">
              <option :value="it.value" v-for="(it,i) in minuteOptions" :key="i">{{it.name}}</option>
            </select>

            <div class="symbol_2">-</div>

            <select v-model="store_work_time[index].endH" class="mySelect">
              <option :value="it.value" v-for="(it,i) in hourOptions" :key="i">{{it.name}}</option>
            </select>
            <div class="symbol_1">:</div>
            <select v-model="store_work_time[index].endM" class="mySelect">
              <option :value="it.value" v-for="(it,i) in minuteOptions" :key="i">{{it.name}}</option>
            </select>

            <uni-icons type="clear" size="20" class="clearIcon" @click="doSelectLine(`remove`,`store_work_time`,index)" v-if="store_work_time.length>1"></uni-icons>

          </div>

          <div class="flexAc addSelectBox" v-if="store_work_time.length<5" @click="doSelectLine(`add`,`store_work_time`)">
              <uni-icons type="plusempty" size="18" color="#2979ff"></uni-icons>
              <div>增加营业时段</div>
          </div>

        </div>

      </uni-forms-item>
      <uni-forms-item name="store_delivery_time" label="配送时段" class="alignFlexStart" required>
        <div class="flexColumn">
          <div class="mySelectBox" v-for="(item,index) in store_delivery_time" :key="index">
            <select v-model="store_delivery_time[index].startH" class="mySelect">
              <option :value="it.value" v-for="(it,i) in hourOptions" :key="i">{{it.name}}</option>
            </select>
            <div class="symbol_1">:</div>
            <select v-model="store_delivery_time[index].startM" class="mySelect">
              <option :value="it.value" v-for="(it,i) in minuteOptions" :key="i">{{it.name}}</option>
            </select>

            <div class="symbol_2">-</div>

            <select v-model="store_delivery_time[index].endH" class="mySelect">
              <option :value="it.value" v-for="(it,i) in hourOptions" :key="i">{{it.name}}</option>
            </select>
            <div class="symbol_1">:</div>
            <select v-model="store_delivery_time[index].endM" class="mySelect">
              <option :value="it.value" v-for="(it,i) in minuteOptions" :key="i">{{it.name}}</option>
            </select>

            <uni-icons type="clear" size="20" class="clearIcon" @click="doSelectLine(`remove`,`store_delivery_time`,index)" v-if="store_delivery_time.length>1"></uni-icons>

          </div>

          <div class="flexAc addSelectBox" v-if="store_delivery_time.length<5" @click="doSelectLine(`add`,`store_delivery_time`)">
              <uni-icons type="plusempty" size="18" color="#2979ff"></uni-icons>
              <div>增加配送时段</div>
          </div>

        </div>
      </uni-forms-item>
      <uni-forms-item name="store_food_finish_time" label="出餐时间" required>
        <uni-data-checkbox mode="button" v-model="formData.store_food_finish_time" :localdata="formOptions.store_food_finish_time_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="store_food_pack_fee" label="餐具费用" required>
        <uni-data-checkbox mode="button" v-model="formData.store_food_pack_fee" :localdata="formOptions.store_food_pack_fee_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="store_food_delivery_fee" label="基础配送费" required>
        <uni-data-checkbox mode="button" v-model="formData.store_food_delivery_fee" :localdata="formOptions.store_food_delivery_fee_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="store_start_delivery_money" label="起送金额" required>
        <uni-data-checkbox  mode="button"  v-model="startSelect" :localdata="selectList"></uni-data-checkbox>
        <div class="flexStyle"  v-if="startSelect!=selectList[0].value">
          <uni-easyinput type="number" prefixIcon="wallet" placeholder="最低配送金额，单位元" v-model="min_delivery_money"></uni-easyinput>
          <div style="margin-left:10rpx">元</div>
        </div>
      </uni-forms-item>
      <uni-forms-item name="commission_percentage" label="店铺抽佣" required>
        <div class="flexStyle">
            <uni-easyinput placeholder="请输入店铺抽佣千分比" v-model="formData.commission_percentage" trim="both"></uni-easyinput>
            <div style="margin-left:5px">‰</div>
        </div>
      </uni-forms-item>
      <uni-forms-item name="store_address_xy" label="地图经纬坐标" required>
        <div class="flexStyleBetween" style="width:100%">
          <div class="flexStyle" style="width: 60%;">
              <uni-easyinput placeholder="请输入经纬度，经度前纬度后逗号分割" v-model="store_address_xy" trim="both"></uni-easyinput>
          </div>
            <div class="flexStyle addSelectBox" style="margin-top:0" @click="goToPage('https://lbs.qq.com/getPoint/#')">
              <uni-icons type="location" size="20" color="#2979ff"></uni-icons>
              <div>点我获取信息</div>
            </div>
        </div>
      </uni-forms-item>
      <uni-forms-item name="store_address_info" label="店铺地址"  class="alignFlexStart" required>
        <div class="storeAddressSelect flexColumn">
          <uni-easyinput  v-model="formData.store_address_info"  type="textarea" placeholder="请输入详细的店铺地址，方便骑手和用户了解" ></uni-easyinput>
          <!-- <div class="flexAc addSelectBox" @click="chooseLocation">
              <uni-icons type="location" size="18" color="#2979ff"></uni-icons>
              <div>点击选择店铺地址</div>
          </div> -->

        </div>
      </uni-forms-item>
      <uni-forms-item name="store_notice" label="店铺公告"  class="alignFlexStart">
        <uni-easyinput type="textarea" placeholder="请输入店铺公告，方便更多人了解您的店铺"  :maxlength="500" v-model="formData.store_notice" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="work_status" label="营业或休息" >
        <uni-data-checkbox v-model="formData.work_status" :localdata="formOptions.work_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="enable_status" label="店铺状态" >
        <uni-data-checkbox v-model="formData.enable_status" :localdata="formOptions.enable_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<style lang="stylus" scoped>
.addSelectBox
  font-size: 22rpx
  margin-top: 15rpx
  cursor pointer
  user-select: none
  color: #2979ff
.storeAddressSelect
  width: 100%
</style>

<script>
  import Big from 'big.js';
  import { validator } from '../../js_sdk/validator/food-merchant-list.js';

  const adminFilesMG = uniCloud.importObject('admin-files-manage',{
      customUI:true
  }) 
  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food-merchant-list';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
            result[key] = validator[key]
      }
    }
    return result
  }

  function createOptions(max){
      const options=[];
      for(let i=0;i<=max;i++){
        let index=i
        if(i<10){
          index=`0${i}`
        }
        options.push({
          name:index,
          value:index
        })
      }
      return options
  }
  
function createValues(){
  return {
          startH:`00`,
          startM:`00`,
          endH:`00`,
          endM:`00`,
        }
}

  export default {
    data() {
      let formData = {
        'enable_status':0,
        'work_status':0,
        'store_address_xy':[],
        "city_code": '',
        "city_id_array":[],

        "store_name": "",
        "store_icon": [],
        "store_plaque_icon": [],
        "store_cover_icon":[],
        "store_phone": "",
        "store_work_date": [
          0
        ],
        "store_work_time": [],
        "store_delivery_time": [],
        "store_food_finish_time": 1200000,
        "store_food_pack_fee": 0,
        "store_food_delivery_fee": 0,
        "store_start_delivery_money": 0,
        "store_address_info": "",
        "store_notice": "",
        "store_category_menuId": [],
        "commission_percentage":10,
      }
      return {
        store_address_xy:``,

        min_delivery_money:20,
        fileList1:null,
        fileList2:null,
        fileList3:null,
        messageText:``,
        startSelect:20,
        selectList:[{
          text: '20元',
					value: 20
        },{
          text: '自定义',
					value: 1
        }],
        hourOptions:createOptions(23),
        minuteOptions:createOptions(59),
        store_work_time:[createValues()],
        store_delivery_time:[createValues()],
        

        formData,
        formOptions: {
          'store_category_menuId_localdata':[],

            'work_status_localdata':[
              {
                "text":"营业",
                "value":0
              },
              {
                "text":"休息",
                "value":1
              }
          ],
          'enable_status_localdata':[
              {
                "text":"审核通过",
                "value":0
              },
              {
                "text":"审核失败",
                "value":1
              },
              {
                "text":"正在审核",
                "value":2
              },
              {
                "text":"异常店铺",
                "value":3
              }
          ],

          "store_work_date_localdata": [
            {
              "text": "周一",
              "value": 0
            },
            {
              "text": "周二",
              "value": 1
            },
            {
              "text": "周三",
              "value": 2
            },
            {
              "text": "周四",
              "value": 3
            },
            {
              "text": "周五",
              "value": 4
            },
            {
              "text": "周六",
              "value": 5
            },
            {
              "text": "周日",
              "value": 6
            }
          ],
          "store_food_finish_time_localdata": [
            {
              "text": "20分钟内",
              "value": 1200000
            },
            {
              "text": "30分钟内",
              "value": 1800000
            },
            {
              "text": "40分钟内",
              "value": 2400000
            },
            {
              "text": "50分钟内",
              "value": 3000000
            },
            {
              "text": "60分钟内",
              "value": 3600000
            }
          ],
          "store_food_pack_fee_localdata": [
            {
              "text": "0元",
              "value": 0
            },
            {
              "text": "1元",
              "value": 100
            },
            {
              "text": "2元",
              "value": 200
            },
            {
              "text": "3元",
              "value": 300
            },
            {
              "text": "4元",
              "value": 400
            },
            {
              "text": "5元",
              "value": 500
            },
            {
              "text": "6元",
              "value": 600
            },
            {
              "text": "7元",
              "value": 700
            },
            {
              "text": "8元",
              "value": 800
            },
            {
              "text": "9元",
              "value": 900
            },
            {
              "text": "10元",
              "value": 1000
            }
          ],
          "store_food_delivery_fee_localdata": [
            {
              "text": "0元",
              "value": 0
            },
            {
              "text": "1元",
              "value": 100
            },
            {
              "text": "2元",
              "value": 200
            },
            {
              "text": "3元",
              "value": 300
            },
            {
              "text": "4元",
              "value": 400
            },
            {
              "text": "5元",
              "value": 500
            },
            {
              "text": "6元",
              "value": 600
            },
            {
              "text": "7元",
              "value": 700
            },
            {
              "text": "8元",
              "value": 800
            },
            {
              "text": "9元",
              "value": 900
            },
            {
              "text": "10元",
              "value": 1000
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    watch:{
      store_address_xy:{
        handler:function(val){
          const list=val.split(',');
          const value=[];
          if(list.length==2){
              for(let i=0;i<list.length;i++){
                const it=list[i].trim();
                if(/^\d+\.\d+?$/.test(it)){
                  value.push(parseFloat(it))
                }
              }
              if(value.length===2){
                return this.formData.store_address_xy=value;
              }
          }
          this.formData.store_address_xy=[];
        },
        immediate:true
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
      this.getHomeMenus();
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      goToPage(path){
        window.open(path)
      },
      async getHomeMenus(){
        const {result:{errCode,data}}= await db.collection(`food-home-menus`).field(`menu_name`).get()
        if(errCode===0){
          const renderList=data.map(it=>{
            return { text:it.menu_name, value:it._id}
          })
          
          this.formOptions.store_category_menuId_localdata=renderList;
        }
        
      },

      chooseLocation(){
          uni.chooseLocation({
              success:(res)=>{
                console.log(res)
              },
              fail:(err)=>{
                console.log(err)
              }
            })
      },
      doSelectLine(type,key,index){
        if(type===`add`){
          this[key].push(createValues())
        }else{
          this[key].splice(index,1);
        }
      },
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then(async (res) => {
          console.log(res)

            if(res.store_icon.length===0&&this.fileList1==null){
                this.messageText=`请上传店铺图标`
                return this.$refs.message.open()
            }

            if(res.store_plaque_icon.length===0&&this.fileList2==null){
                this.messageText=`请上传店铺牌匾图片`
                return this.$refs.message.open()
            }

            if(res.store_cover_icon.length===0&&this.fileList3==null){
                this.messageText=`请上传店铺封面图片`
                return this.$refs.message.open()
            }

          if(this.startSelect==this.selectList[0].value){ //选择金额
            res.store_start_delivery_money=+new Big(this.selectList[0].value).times(100)
          }else{
            // 手动输入金额
            if(this.min_delivery_money===``){
                this.messageText=`起送金额不能为空，请重新输入`
                return this.$refs.message.open()
            }
            if(isNaN(this.min_delivery_money)){
              this.messageText=`起送金额必须是数字，请重新输入`
              return this.$refs.message.open()
            }
            res.store_start_delivery_money=+new Big(this.min_delivery_money).times(100)
          }

          if(this.fileList1!=null){
              await adminFilesMG.removeFile({
                  table:dbCollectionName,
                  id:[this.formDataId],
                  field:`store_icon`
                });
              res.store_icon= await this.$refs.files1.upload()
            }
            
            if(this.fileList2!=null){
              await adminFilesMG.removeFile({
                  table:dbCollectionName,
                  id:[this.formDataId],
                  field:`store_plaque_icon`
              });
              res.store_plaque_icon= await this.$refs.files2.upload();
            }         

            if(this.fileList3!=null){
              await adminFilesMG.removeFile({
                  table:dbCollectionName,
                  id:[this.formDataId],
                  field:`store_cover_icon`
              });
              res.store_cover_icon= await this.$refs.files3.upload();
            }

          res.city_id_array=this.formData.city_id_array
          res.store_work_time= this.store_work_time;
          res.store_delivery_time= this.store_delivery_time

          return this.submitForm(res)
        }).catch((e) => {
          console.log(e)
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("commission_percentage,store_category_menuId,store_cover_icon,city_id_array,city_code,store_address_xy,enable_status,work_status,store_name,store_icon,store_plaque_icon,store_phone,store_work_date,store_work_time,store_delivery_time,store_food_finish_time,store_food_pack_fee,store_food_delivery_fee,store_start_delivery_money,store_address_info,store_notice").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            const server_delivery_money=+new Big(data.store_start_delivery_money).div(100)
            data.store_start_delivery_money=0
            this.store_work_time=data.store_work_time;
            this.store_delivery_time=data.store_delivery_time;

            if(this.selectList[0].value!=server_delivery_money){
                this.startSelect=this.selectList[1].value
                this.min_delivery_money=server_delivery_money
            }

            this.store_address_xy=data.store_address_xy.join(',')

            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
